package com.atguigu.tingshu.user.pattern.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.pattern.UserPaidStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2024-03-09 11:35
 */
@Slf4j
@Component(SystemConstant.ORDER_ITEM_TYPE_TRACK)
public class TrackUserPaidStrategy implements UserPaidStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    /**
     * 处理购买项目类型：声音
     *
     * @param userPaidRecordVo
     */
    @Override
    public void saveUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("理购买项目类型：声音,{}", userPaidRecordVo);
        //2.处理声音购买记录
        //2.1 根据订单编号查询已购声音记录 如果购买记录存在说明已经保存过则忽略
        LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        userPaidTrackLambdaQueryWrapper.last("limit 1");
        Long count = userPaidTrackMapper.selectCount(userPaidTrackLambdaQueryWrapper);
        if (count > 0) {
            return;
        }
        //2.3 根据声音ID声音信息
        TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
        //2.3 遍历已购声音ID列表构建用户已购声音记录，保存已购声音记录
        userPaidRecordVo.getItemIdList()
                .stream().forEach(trackId -> {
                    UserPaidTrack userPaidTrack = new UserPaidTrack();
                    userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                    userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                    userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                    userPaidTrack.setTrackId(trackId);
                    userPaidTrackMapper.insert(userPaidTrack);
                });
    }
}
